package com.example.demo.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 调用依赖服务，通过hystrix包装调用服务
 * @author LiYiGuang
 * @date 2019/4/17 11:22
 */
@Component
public class CallDependencyService {
    private Random random = new Random();
    /**
     * 模拟获取用户信息(通过网络调用)
     * @return
     */
    @HystrixCommand(fallbackMethod = "fallback",commandProperties={@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="5000")})
    public String mockGetUserInfo(){
        int randomInt= random.nextInt(10) ;
        try {
            Thread.sleep(randomInt*1000L);
        } catch (InterruptedException e) {

        }
//        if(randomInt<8){  //模拟调用失败情况
//            throw new RuntimeException("call dependency service fail.");
//        }else{
            return "UserName:liyg;number:"+randomInt;
//        }
    }

    public String fallback(){
        System.out.println(Thread.currentThread());
        return "some exception occur call fallback method.";
    }
}
